// 'use strict';
angular.module('indexApp', ['ui.router', 'oc.lazyLoad', 'ui.bootstrap', 'infinite-scroll'])

    .config(function ($urlRouterProvider, $stateProvider, $ocLazyLoadProvider, $locationProvider) {
        // cfpLoadingBarProvider.spinnerTemplate = '<div><span class="fa fa-spinner">Loading...</div>';

        function lazyLoad(url) {
            return function ($ocLazyLoad) {
                return $ocLazyLoad.load({
                    files: url,
                    serie: true
                })
            }
        }

        // $rootScope.$on("$routeChangeSuccess", function(currentRoute, previousRoute){
        //     $rootScope.pageTitle = $route.current.data.pageTitle;
        // });
        $ocLazyLoadProvider.config({
            debug: false,
            events: true
        });
        $urlRouterProvider.otherwise('/main/home');

        $stateProvider
            .state('login', {
                url: '/login',
                title: '登录',
                data: {pageTitle: '登录'},//设置页面标题
                templateUrl: 'view/login.html',
                // controller: 'loginCtrl',
                controllerAs: 'vm',
                resolve: {
                    load: lazyLoad([
                        'css/login.css'
                        ,
                        'js/controllers/login.js'
                    ])
                }
            })
            .state('registered', {
                url: '/registered',
                title: '注册报名',
                data: {pageTitle: '注册报名'},//设置页面标题
                templateUrl: 'view/registered.html',
                // controller: 'registeredCtrl',
                controllerAs: 'vm',
                resolve: {
                    load: lazyLoad([
                        'css/registered.css'
                        , 'node_modules/time_picker.css', 'node_modules/time_picker.js',
                        'js/controllers/registered.js'
                    ])
                }
            })
            .state('main', {
                url: '/main',
                title: '主页',
                data: {pageTitle: '主页'},//设置页面标题
                templateUrl: 'view/main.html',
                abstract: true, // true 表明此状态不能被显性激活，只能被子状态隐性激活
                // controller: 'mainCtrl',
                controllerAs: 'vm',
                resolve: {
                    load: lazyLoad([
                        'css/main.css'
                        ,
                        'js/controllers/main.js'
                    ])
                }
            })
            .state('main.home', {
                url: '/home',
                title: '首页',
                data: {pageTitle: '首页'},//设置页面标题
                templateUrl: 'view/main/home.html',
                // controller: 'homeCtrl',
                controllerAs: 'vm',
                resolve: {
                    load: lazyLoad([
                        'css/main/home.css'
                        , 'https://cdnjs.cloudflare.com/ajax/libs/Swiper/3.0.1/css/swiper.css', 'https://cdnjs.cloudflare.com/ajax/libs/Swiper/3.0.1/js/swiper.js'
                        ,
                        'js/controllers/main/home.js'
                    ])
                }
            })
            .state('main.sortAll', {
                url: '/sortAll',
                title: '分类',
                data: {pageTitle: '分类'},//设置页面标题
                templateUrl: 'view/main/sortAll.html',
                // controller: 'sortCtrl',
                controllerAs: 'vm',
                resolve: {
                    load: lazyLoad([
                        'css/main/sortAll.css'
                        ,
                        'js/controllers/main/sortAll.js'
                    ])
                }
            })
            // detail与main平级的路由
            .state('detail', {
                url: '/detail',
                title: '详情页',
                data: {pageTitle: '详情页'},//设置页面标题
                templateUrl: 'view/detail.html',
                abstract: true, // true 表明此状态不能被显性激活，只能被子状态隐性激活
                resolve: {
                    load: lazyLoad([
                        'css/detail.css'
                        ,
                        'js/controllers/detail.js'
                    ])
                }
            })
            .state('detail.invite_register', {
                url: '/invite_register',
                title: '邀请注册',
                data: {pageTitle: '邀请注册'},//设置页面标题
                templateUrl: 'view/detail/invite_register.html',
                // controller: 'goodsDetailCtrl',
                controllerAs: 'vm',
                resolve: {
                    load: lazyLoad([
                        'css/detail/invite_register.css'
                        ,
                        'js/controllers/detail/invite_register.js'
                    ])
                }
            })
            .state('detail.all_activity', {
                url: '/all_activity',
                title: '所有活动',
                data: {pageTitle: '所有活动'},//设置页面标题
                templateUrl: 'view/detail/all_activity.html',
                // controller: 'goodsDetailCtrl',
                controllerAs: 'vm',
                resolve: {
                    load: lazyLoad([
                        'css/detail/all_activity.css'
                        ,
                        'js/controllers/detail/all_activity.js'
                    ])
                }
            })
            .state('detail.activity_detail', {
                url: '/activity_detail/:id',
                title: '活动详情',
                data: {pageTitle: '活动详情'},//设置页面标题
                templateUrl: 'view/detail/activity_detail.html',
                // controller: 'goodsDetailCtrl',
                controllerAs: 'vm',
                resolve: {
                    load: lazyLoad([
                        'css/detail/activity_detail.css'
                        ,
                        'js/controllers/detail/activity_detail.js'
                    ])
                }
            })
            .state('detail.apply_activity', {
                url: '/apply_activity/:id',
                title: '报名信息',
                data: {pageTitle: '报名信息'},//设置页面标题
                templateUrl: 'view/detail/apply_activity.html',
                // controller: 'registeredCtrl',
                controllerAs: 'vm',
                resolve: {
                    load: lazyLoad([
                        'css/detail/apply_activity.css'
                        , 'node_modules/time_picker.css', 'node_modules/time_picker.js',
                        'js/controllers/detail/apply_activity.js'
                    ])
                }
            })
            .state('main.loseWeight', {
                url: '/loseWeight',
                title: '减肥排行榜',
                data: {pageTitle: '减肥排行榜'},//设置页面标题
                templateUrl: 'view/main/loseWeight.html',
                // controller: 'shopCarCtrl',
                controllerAs: 'vm',
                resolve: {
                    load: lazyLoad([
                        'css/main/loseWeight.css'
                        ,
                        'js/controllers/main/loseWeight.js'
                    ])
                }
            })
            .state('main.personal', {
                url: '/personal',
                title: '我的',
                data: {pageTitle: '个人中心'},//设置页面标题
                templateUrl: 'view/main/personal.html',
                // controller: 'personalCtrl',
                controllerAs: 'vm',
                resolve: {
                    load: lazyLoad([
                        'css/main/personal.css?v=1'
                        ,
                        'js/controllers/main/personal.js'
                    ])
                }
            })
            .state('detail.witness_list', {
                url: '/witness_list',
                title: '邀请见证',
                data: {pageTitle: '邀请见证'},//设置页面标题
                templateUrl: 'view/detail/witness_list.html',
                // controller: 'registeredCtrl',
                controllerAs: 'vm',
                resolve: {
                    load: lazyLoad([
                        'css/detail/witness_list.css'
                        ,
                        'js/controllers/detail/witness_list.js'
                    ])
                }
            })
            //邀请朋友见证
            .state('detail.invite_friend', {
                url: '/invite_friend',
                title: '邀请见证',
                data: {pageTitle: '邀请见证'},//设置页面标题
                templateUrl: 'view/detail/invite_friend.html',
                // controller: 'registeredCtrl',
                controllerAs: 'vm',
                resolve: {
                    load: lazyLoad([
                        'css/detail/invite_friend.css'
                        ,
                        'js/controllers/detail/invite_friend.js'
                    ])
                }
            })
            .state('detail.my_activity', {
                url: '/my_activity',
                title: '我的活动',
                data: {pageTitle: '我的活动'},//设置页面标题
                templateUrl: 'view/detail/my_activity.html',
                // controller: 'registeredCtrl',
                controllerAs: 'vm',
                resolve: {
                    load: lazyLoad([
                        'css/detail/my_activity.css'
                        ,
                        'js/controllers/detail/my_activity.js'
                    ])
                }
            })
            .state('detail.invite_edit', {
                url: '/invite_edit',
                title: '邀请见证',
                data: {pageTitle: '邀请见证'},//设置页面标题
                templateUrl: 'view/detail/invite_edit.html',
                // controller: 'registeredCtrl',
                controllerAs: 'vm',
                resolve: {
                    load: lazyLoad([
                        'css/detail/invite_edit.css'
                        ,
                        'js/controllers/detail/invite_edit.js'
                    ])
                }
            })
            .state('detail.awardsExplain', {
                url: '/awardsExplain',
                title: '奖项说明',
                data: {pageTitle: '奖项说明'},//设置页面标题
                templateUrl: 'view/detail/awardsExplain.html',
                // controller: 'registeredCtrl',
                controllerAs: 'vm',
                resolve: {
                    load: lazyLoad([
                        'css/detail/awardsExplain.css'
                        ,
                        'js/controllers/detail/awardsExplain.js'
                    ])
                }
            })
            .state('detail.curves', {
                url: '/curves',
                title: '减肥曲线',
                data: {pageTitle: '减肥曲线'},//设置页面标题
                templateUrl: 'view/detail/curves.html',
                // controller: 'registeredCtrl',
                controllerAs: 'vm',
                resolve: {
                    load: lazyLoad([
                        'css/detail/curves.css'
                        , 'https://cdn.bootcss.com/echarts/4.1.0.rc2/echarts-en.common.js',
                        'js/controllers/detail/curves.js'
                    ])
                }
            })
            .state('detail.housesIntroduce', {
                url: '/housesIntroduce',
                title: '楼盘介绍',
                data: {pageTitle: '楼盘介绍'},//设置页面标题
                templateUrl: 'view/detail/housesIntroduce.html',
                // controller: 'registeredCtrl',
                controllerAs: 'vm',
                resolve: {
                    load: lazyLoad([
                        'css/detail/housesIntroduce.css'
                        , 'https://cdnjs.cloudflare.com/ajax/libs/Swiper/3.0.1/css/swiper.css', 'https://cdnjs.cloudflare.com/ajax/libs/Swiper/3.0.1/js/swiper.js'
                        ,
                        'js/controllers/detail/housesIntroduce.js'
                    ])
                }
            })
            .state('detail.integral', {
                url: '/integral',
                title: '积分明细',
                data: {pageTitle: '积分明细'},//设置页面标题
                templateUrl: 'view/detail/integral.html',
                // controller: 'registeredCtrl',
                controllerAs: 'vm',
                resolve: {
                    load: lazyLoad([
                        'css/detail/integral.css'
                        ,
                        'js/controllers/detail/integral.js'
                    ])
                }
            })
            .state('detail.invite', {
                url: '/invite',
                title: '我的邀请',
                data: {pageTitle: '我的邀请'},//设置页面标题
                templateUrl: 'view/detail/invite.html',
                // controller: 'registeredCtrl',
                controllerAs: 'vm',
                resolve: {
                    load: lazyLoad([
                        'css/detail/invite.css'
                        ,
                        'js/controllers/detail/invite.js'
                    ])
                }
            })
            .state('detail.gift', {
                url: '/gift/:is_verification',
                title: '核销',
                data: {pageTitle: '核销'},//设置页面标题
                templateUrl: 'view/detail/gift.html',
                // controller: 'registeredCtrl',
                controllerAs: 'vm',
                resolve: {
                    load: lazyLoad([
                        'css/detail/gift.css'
                        ,
                        'js/controllers/detail/gift.js'
                    ])
                }
            });

        // $locationProvider.html5Mode(true);//启用html5模式<!--去掉#-->
    })
    .run(['$rootScope', '$log', '$state', '$http', '$stateParams', '$location', function ($rootScope, $log, $state, $http, $stateParams, $location, $scope) {
        $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
            //跳转到页面顶部
            // scrollTo(0, 0);
            //detail页面数据
            $rootScope.detailTitle = toState.title;
            $rootScope.title = toState.data.pageTitle;
            $rootScope.http = 'http://193.112.111.73/api/index/';
            $rootScope.http_main = 'http://fangdichan.whtxcloud.com';
            sessionStorage.http = $rootScope.http;

            // $rootScope.id = 10;


            function getCookieValue2(name) {
                var result = document.cookie.match('(^| )' + name + '=([^;]*)(;|$)');
                if (result) {
                    // /*
                    //  此处需要注意两点
                    //  一.如果保存cookie值的时候使用了escape()进行了编码，就记得使用unescape()进行解码
                    //  二.需要对match()函数的返回结果熟悉
                    //  */
                    return unescape(result[2]);
                } else {
                    return null;
                }
            }

            //获取邀请人的id
            function getRequest1() {
                var str = location.search; //  ?userName=zhanghao$userId=123
                if (str) {
                    var url = str.substr(1), arr = url.split('&'), len = arr.length, i = 0, request = {};
                    //        ["userName=zhanghao", "userId=123"]
                    for (; i < len; i++) {
                        request[arr[i].split('=')[0]] = arr[i].split('=')[1];
                        //           ["userName", "zhanghao"]  ["userId", "123"]
                    }
                    return request; //{userName: "zhanghao", userId: "123"}
                } else {
                    // alert('没有传递参数');
                }
            }
            if(localStorage.getItem('id')){
                var Request = {invite_id: ''};
                Request = getRequest1();//可以查看返回的对象，根据对象的参数获取其中的键值对
                if (Request.invite_id) {
                    localStorage.invite_id = Request.invite_id;
                } else if (Request.witness_id) {
                    sessionStorage.witness_id = Request.witness_id;
                    console.log(Request.witness_id)
                }
                console.log(Request, '123');
                var invite_id = localStorage.invite_id || '';
                console.log(invite_id);

                $http({
                    method: 'post',
                    url: sessionStorage.http + 'get_userinfo',
                    data: {
                        user_id: $rootScope.id
                    }
                })
                    .then(function successCallback(res) {
                        console.log(res.data);
                        if (res.data.code == 0) {
                            localStorage.setItem("avatar", res.data.data.user.avatar);
                            if (sessionStorage.witness_id) {
                                if (res.data.data.user.is_com == 0) {
                                    $state.go('registered')
                                } else {
                                    // window.location.href = $rootScope.http_main + '/#/detail/invite_friend';
                                }
                            }
                        }
                    }, function errorCallback(res) {// 请求失败执行代码
                        // $rootScope.alertError()
                    });

            }
            if (!localStorage.getItem("id")) {

                var Request = {invite_id: ''};
                Request = getRequest1();//可以查看返回的对象，根据对象的参数获取其中的键值对
                if (Request.invite_id) {
                    localStorage.invite_id = Request.invite_id;
                } else if (Request.witness_id) {
                    sessionStorage.witness_id = Request.witness_id;
                    console.log(Request.witness_id)
                }
                console.log(Request, '123');
                var invite_id = localStorage.invite_id || '';
                console.log(invite_id);
                // alert(r[2])
                var reg = new RegExp("(^|&)code=([^&]*)(&|$)");
                var r = window.location.search.substr(1).match(reg);
                if (r) {
                    // $rootScope.alert(r[2]);
                    $http({
                        method: 'post',
                        url: $rootScope.http + 'user_login',
                        data: {
                            code: r[2],
                            // invite_id: invite_id
                        }
                    }).then(function successCallback(res) {
                        console.log(res.data);

                        // $rootScope.id = res.data.data.id;
                        // $rootScope.alert(res.data.data.id);
                        // localStorage.setItem("id", res.data.data.id);
                        // $rootScope.alert($rootScope.id);
                        if (res.data.code == 0) {
                            //获取用户信息
                            //获取个人信息
                            localStorage.setItem("avatar", res.data.data.user.avatar);
                            localStorage.setItem("id", res.data.data.user.id);
                            sessionStorage.setItem("id", res.data.data.user.id);
                            sessionStorage.setItem("is_com", res.data.data.user.is_com);
                            // 根据url后面获取的值来判断跳转页面
                            if (sessionStorage.witness_id) {
                                if (sessionStorage.getItem('is_com') == 0) {
                                    // window.location.href = $rootScope.http_main + '/#/registered';
                                    $state.go('registered')
                                } else {
                                    // window.location.href = $rootScope.http_main + '/#/detail/invite_friend';
                                    // $state.go('detail.invite_friend')
                                }
                            } else if (sessionStorage.house == 1) {
                                // window.location.href = $rootScope.http_main + '/#/detail/housesIntroduce';
                                $state.go('detail.housesIntroduce')
                                // alert('house')
                            } else if (sessionStorage.regist == 1) {
                                // window.location.href = $rootScope.http_main + '/#/registered';
                                $state.go('registered')
                                // alert('house')
                            } else {
                                // window.location.href = $rootScope.http_main + '/#/main/home';
                                // alert('home')
                            }
                            console.log(localStorage.getItem("id"), '刷新');
                            // $rootScope.id = localStorage.getItem("id")
                        }
                        else {
                            $rootScope.alert(res.data.msg);
                        }

                    }, function errorCallback(res) {// 请求失败执行代码
                        bootbox.alert({
                            title: '<p style="color: #47c6e8">提示</p>',
                            message: '请求失败，请稍后重试',
                            buttons: {
                                ok: {
                                    label: '确定',
                                    className: 'btn-primary'
                                }
                            }
                        });
                    });
                }
                else {
                    window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxa5e230c798925e6e&redirect_uri=' + $rootScope.http_main + '&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
                }

            }
        });
        //alert弹出框
        $rootScope.alert = function (data, fn) {
            if (data != undefined || data != null) {
                fn = data == undefined ? ' ' : fn;
                bootbox.alert({
                    title: '操作提示',
                    message: data,
                    buttons: {
                        ok: {
                            label: '确认'
                        }
                    },
                    callback: fn
                });
            }
        };
        $rootScope.alertError = function () {
            bootbox.alert({
                title: '<p style="color: #47c6e8;font-size: 32px">提示</p>',
                message: '请稍后重试',
                buttons: {
                    ok: {
                        label: '确定',
                        className: 'btn-primary'
                    }
                }
            });
        }
    }]);